package com.efrei.uchat.client.term;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import com.efrei.uchat.client.UChatClient;
import com.efrei.uchat.client.UChatClient.UChatStatus;
import com.efrei.uchat.client.UChatUI;
import com.efrei.uchat.message.CroomMessage;
import com.efrei.uchat.message.CroomUsersMessage;
import com.efrei.uchat.message.CroomsMessage;
import com.efrei.uchat.message.LoginMessage;
import com.efrei.uchat.message.TextMessage;
import com.efrei.uchat.model.croom.CroomMessageStatus;

public class TermReader extends UChatUI implements Runnable {

	private static Logger logger = Logger.getLogger(TermReader.class);
	
	private BufferedReader reader;
	private boolean waiting = false;
	
	public TermReader(UChatClient context) {
		super();
		this.reader = new BufferedReader(new InputStreamReader(System.in));
	}
	
	@Override
	public void run() {
		logger.debug("BEGIN OF TermReader");
		UChatStatus status;
		while((status = getContextStatus()) != UChatStatus.DISCONNECT) {
			if(waiting) {
				// waiting context response
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
					disconnect();
				}
			} else {
				// context status
				switch (status) {
				case INIT:
					init();
					break;
				default:
					waitingMessage();
					break;
				}
			}
		}
		logger.debug("END OF TermReader");
	}
	
	private void init() {
		try {
			String login = "";
			
			// croom
			logger.debug("Enter login :");
			login = reader.readLine();
			
			if(login==null) {
				disconnect();
			} else {
				waiting = true;
				loginRequest(login);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void waitingMessage() {
		try {
			String command;
			
			// croom
			logger.debug("Enter message :");
			command = reader.readLine();
			
			// message
			if(command==null) {
				disconnect();
			} else {
				//waiting = true;
				sendMessage("public", command);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void receivedLoginMessage(LoginMessage message) {
		String login = message.getLogin();
		if(message.isValid()) {
			logger.debug("Login completed: "+login);
		} else {
			logger.debug("Login failed: "+login);
		}
		waiting = false;
	}

	@Override
	public void receivedTextMessage(TextMessage message) {
		logger.debug(
				String.format("%s: %s said %s",
						message.getCroom(),
						message.getAuthor(),
						message.getText()));
	}

	@Override
	public void receivedCroomList(CroomsMessage message) {
		StringBuilder bb = new StringBuilder();
		bb.append("BEGIN CROOMS LIST\n");
		for (String croom : message.getCrooms().keySet()) {
			bb.append("\t"+croom+"\n");
		}
		logger.debug(bb.append("END OF LIST\n").toString());
	}

	@Override
	public void receivedCroomUsers(CroomUsersMessage message) {
		StringBuilder bb = new StringBuilder();
		bb.append("BEGIN USERS LIST FOR "+message.getCroom()+"\n");
		for (String user : message.getUsers().keySet()) {
			bb.append("\t"+user+"\n");
		}
		logger.debug(bb.append("END OF LIST\n").toString());
	}

	@Override
	public void croomResult(CroomMessage message) {
		if(message.getStatus()==CroomMessageStatus.SUCCESS) {
			logger.debug("Join croom "+message.getCroom());
		} else {
			logger.debug("Failed to join croom "+message.getCroom());
		}
	}

	@Override
	public void disconnect() {
		logger.debug("TermReader: disconnected");
	}
}
